import {IndexConfig} from "@/core/indexDB/@type/index.d";
import {getDataBaseVersion, openConnect} from "@/core/indexDB/dataBase";

/**
 * 创建表
 * @param dataBaseName 数据库名称
 * @param tableName 表名称
 * @param primaryKey 主键key
 * @param indexList 插入的数据
 */
export const creatObjectStore = async ( dataBaseName:string, tableName:string, primaryKey?:string, indexList?:IndexConfig[] ) => {
    return new Promise( async (resolve, reject) => {
        const version = await getDataBaseVersion(dataBaseName)
        const res = await openConnect(dataBaseName,(event: IDBVersionChangeEvent) => {
            const idb = (event?.target as IDBOpenDBRequest)?.result
            const objectStore = idb?.createObjectStore(tableName,primaryKey ? {  keyPath:primaryKey } : {autoIncrement: true} )
            if(indexList && indexList.length)  indexList.forEach( ele => { objectStore?.createIndex(ele.name, ele.name, ele.option)}) // 创建索引
        },Number(version) + 1)
        resolve(res)
    })
}

/**
 * 删除表
 * @param dataBaseName 数据库名称
 * @param tableName 表名称
 */
export const deleteObjectStore = async (dataBaseName:string, tableName:string) => {
    return new Promise( async (resolve, reject) => {
        const version = await getDataBaseVersion(dataBaseName)
        const res = await openConnect(dataBaseName,  (event: IDBVersionChangeEvent) => {
            const idb = (event?.target as IDBOpenDBRequest)?.result
            idb?.deleteObjectStore(tableName)
        },Number(version) + 1)
        resolve(res)
    })
}